<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use App\Service\DyCouponService;
use App\Service\UserService;
use App\Service\PlayletService;
#[AutoController]
class DyCouponController extends BaseController
{
    #[Inject]
    private UserService $userService;
    #[Inject]
    private DyCouponService $dyCouponService;
    #[Inject]
    private PlayletService $playletService;


    /**
     * 用户领券结果回调通知,插入数据库信息
     * author bobo
     * date 2024-03-29
    */
    public function callback(RequestInterface $request, ResponseInterface $response){


        $timestamp = $request->getHeader('Byte-Timestamp')[0];
        $nonce_str = $request->getHeader('Byte-Nonce-Str')[0];
        $sign = $request->getHeader('Byte-Signature')[0];

        $postData = $request->post();
        $http_body = json_encode($postData);
        var_dump('----------------抖音用户券信息推送');
//        var_dump('Byte-Timestamp-----------:'.$timestamp);
//        var_dump('Byte-Nonce-Str-----------:'.$nonce_str);
//        var_dump('Byte-Signature-----------:'.$sign);
//        var_dump('body-----------:'.$http_body);

        $allData = [

            'timestamp' => $timestamp,
            'nonce_str' => $nonce_str,
            'sign' => $sign,
            'http_body' => $postData,
        ];
        $this->dyCouponService->redisService->lPush('coupon_post_list',json_encode($allData));

        //先查询小程序ID
        $msg = $postData['msg'];
        $jsonData = json_decode($msg,true);
        $returnData = ["err_no"=> 400,'err_msg' => 'system error','notify_status' => 'fail'];
        if(!empty($jsonData)){
            $app_id = $jsonData['app_id'];
            $appletInfo = Db::table('applet')->select('id')->where('app_id',$app_id)->first();
            if(!empty($appletInfo)){
                $verifySign = $this->verify($http_body, $timestamp, $nonce_str, $sign,$appletInfo->id);
                if($verifySign){
                    $type = $postData['type'] ?? '';
                    //判断为send_coupon 为获取用户领取成功
                    if($type == 'send_coupon'){
                        $result = $this->dyCouponService->insertCoupon($postData);
                        $returnData = $result;
                    }
                }
            }
        }


        return json_encode($returnData);
    }
    /**
     * 用户领券结果回调通知,验证签名
     * author bobo
     * date 2024-03-29
     */
    public function verify($http_body, $timestamp, $nonce_str, $sign,$applet_id)
    {
        $data = $timestamp . "\n" . $nonce_str . "\n" . $http_body . "\n";
        $privateUrl = "/home/wwwroot/ml_api/dy/".$applet_id."/platform_public_key.pem";
        $publicKey = file_get_contents($privateUrl);
        if (!$publicKey) {
            return null;
        }
        $res = openssl_get_publickey($publicKey); // 注意验签时publicKey使用平台公钥而非应用公钥
        $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
        return $result;  //bool
    }


    /**
     * 用户核销券
     * author bobo
     * date 2024-04-01
     */
    public function consume(RequestInterface $request,ResponseInterface $response) {
        $coupon_id = $request->input("coupon_id","0");
        $applet_id = $this->get_applet_id();
        $playlet_id = $request->input('playlet_id', 0);
        $playlet_number = $request->input('playlet_number', 0);
        $xc_open_id = $request->input("xc_open_id","");
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $user_id = !empty($open_id_info['id']) ? $open_id_info['id'] : "";
        if (empty($user_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        if (empty($coupon_id)){
            return $this->resultResponse(["code"=>20004]);
        }
        if (empty($playlet_number)){
            return $this->resultResponse(["code"=>20004]);
        }

        $playletInfo = $this->playletService->get_playlet_info($playlet_id);
        var_dump('------短剧为');
        var_dump($playletInfo);
        if(!empty($playletInfo)){
            //查询是否有对应的用户的优惠券
            $couponInfo = $this->dyCouponService->getUserCoupon($coupon_id,$applet_id,$user_id);
            var_dump('------用户券');
            var_dump($couponInfo);
            if(!empty($couponInfo)) {
                //核销这个券
                $consumeResult = $this->dyCouponService->consumeCoupon($couponInfo,$xc_open_id);

                var_dump('------核销券回调');
                if($consumeResult['err_no'] != 0) {
                    return $this->resultResponse(["code"=>20004]);
                }else{
                    var_dump('------核销券回调 成功');
                    //修改这个券为用过
                    Db::table('data_user_coupon')->where(['id' => $couponInfo->id])->update(['is_use' => 'Y','consume_at' => date('Y-m-d H:i:s',time())]);

                    //核销成功，解锁集数
                    $unlockResult = $this->dyCouponService->unlockEpisodes($couponInfo,$playlet_id,$playlet_number,$user_id,$applet_id);
                    if(!empty($unlockResult)){
                        //更新播放列表
                        $this->playletService->up_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                    }
                }
                return $this->resultResponse(["data"=>[]]);
            } else {
                return $this->resultResponse(["code"=>20004]);
            }
        }else{
            return $this->resultResponse(["code"=>20004]);
        }

    }
}